package com.mpp.admin.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author mapp
 * @des
 * @date 2019/2/20
 */
public class RedisSessionDao extends AbstractSessionDAO {

    private RedisCache<Session> redisCache;

    private String keyPrefix = "session_pre";

    public RedisSessionDao(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        saveSession(session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable serializable) {
        return redisCache.get(keyPrefix + serializable);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        saveSession(session);
    }

    @Override
    public void delete(Session session) {
        delete((String) session.getId());
    }

    public void delete(String id) {
        redisCache.remove(id);
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<Session> sessions = new HashSet<>();
        Set<String> keys = redisCache.keys();
        for (String key : keys) {
            sessions.add(redisCache.get(key));
        }
        return sessions;
    }

    private void saveSession(Session session) throws UnknownSessionException{
        if (session == null || session.getId() == null) {
            return;
        }
        //设置过期时间
        long expireTime = 1800000L;
        session.setTimeout(expireTime);
        redisCache.put((String) session.getId(), session);
    }
}
